CO_SRCS := $(wildcard *.cpp)
CO_OBJS := $(patsubst %.cpp,%.o,$(CO_SRCS))
#CO_OBJS := $(CO_SRCS:.cpp=.o)

CO_HOOK_SRCS := $(wildcard hook/*.cpp)
CO_HOOK_SRCS := $(notdir $(CO_HOOK_SRCS))
CO_HOOK_OBJS := $(patsubst %.cpp,%.o,$(CO_HOOK_SRCS))

COMMON_SRCS := $(wildcard common/*.cpp)
COMMON_SRCS := $(notdir $(COMMON_SRCS))
COMMON_OBJS := $(patsubst %.cpp,%.o,$(COMMON_SRCS))

FLAGS=-std=c++11 -O2 -g
SO_FLAGS=-std=c++11 -O2 -g -fPIC

all: make_dir make_so make_test

make_dir:
	test -d ./lib || mkdir -p ./lib
	test -d ./obj || mkdir -p ./obj
	echo $(CO_HOOK_OBJS)

make_so: $(CO_OBJS) $(CO_HOOK_OBJS) $(COMMON_OBJS)
	cd ./obj && g++ $(FLAGS) -fPIC -shared -o ../lib/libco.so $(CO_OBJS) $(CO_HOOK_OBJS) $(COMMON_OBJS) -ldl -lpthread

make_test: make_so
	cd test && g++ $(FLAGS) -o test test.cpp -I../ ../lib/libco.so -lpthread
	cd test && g++ $(FLAGS) -o socket socket.cpp -I../ ../lib/libco.so -lpthread
#	cd test && g++ $(FLAGS) -o client client.cpp -DUSE_THREAD -I../ ../lib/libco.so -lpthread
#	cd test && g++ $(FLAGS) -o server server.cpp -DUSE_THREAD -I../ ../lib/libco.so -lpthread
	cd test && g++ $(FLAGS) -o client client.cpp -I../ ../lib/libco.so -lpthread
#	cd test && g++ $(FLAGS) -o server server.cpp -I../ ../lib/libco.so -lpthread
	cd test && g++ $(FLAGS) -o server server.cpp -I../ -DUSE_THREAD -lpthread
	cd test && g++ $(FLAGS) -o echo_server echo_server.cpp -I../ ../lib/libco.so -lpthread
	cd test && g++ $(FLAGS) -o echo_client echo_client.cpp -I../ ../lib/libco.so -lpthread
#	cd test && g++ $(FLAGS) -o echo_client echo_client.cpp -DUSE_THREAD -I../ -lpthread
#	cd test && g++ $(FLAGS) -o echo_server echo_server.cpp -DUSE_THREAD -I../ ../lib/libco.so -lpthread

$(CO_OBJS):%.o: %.cpp
	g++ $(SO_FLAGS) -o ./obj/$@ -c $<

$(CO_HOOK_OBJS):%.o: ./hook/%.cpp
	g++ $(SO_FLAGS) -o ./obj/$@ -c $<

$(COMMON_OBJS):%.o: ./common/%.cpp
	g++ $(SO_FLAGS) -o ./obj/$@ -c $<

clean:
	rm -f main
	rm -f ./test/*.o
	rm -f ./test/test
	rm -f ./test/socket
	rm -f ./test/client
	rm -f ./test/server
	rm -f ./test/echo_client
	rm -f ./test/echo_server
	rm -rf obj/*
	rm -rf lib/*
